/**
 * Created by XianTao on 2015/2/11
 *
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package com.taotao.wechat.game;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.PlayGame;
import com.taotao.rop.response.BaseResponse;
import com.taotao.rop.util.DateTimeUtil;
import com.taotao.wechat.message.resp.BaseMessage;
import com.taotao.wechat.message.resp.TextMessage;
import com.taotao.wechat.util.MessageUtil;
import com.taotao.wechat.util.ValidateUtil;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

public class ShareOneImage extends Game {
    public static boolean IS_ENABLE = true;
    private final String descImgFolder = "/opt/cmcc_root/webapps/" + getNickName();

    public ShareOneImage() {}

    public ShareOneImage(BaseMessage baseMessage, String content, String appKey) {
        super(baseMessage, content, appKey);
    }

    protected String inputGameName2() {
        if (!content.equalsIgnoreCase(getName())) {
            return "";
        }
        //插入playgame表，准备开始游戏
        PlayGame playGame = new PlayGame();
        playGame.setAppId(appKey);
        playGame.setOpenId(baseMessage.getToUserName());
        playGame.setGameName(getNickName());
        MyRopClient.getRopClient("").buildClientRequest()
                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");

        TextMessage textMessage = new TextMessage(baseMessage);
        textMessage.setContent(getMsgAfterGameName());
        return MessageUtil.textMessageToXml(textMessage);
    }

    protected String inputTelephone2() {
        //判断属于哪款游戏
        String currentGameName = getLatestInputGameName(baseMessage.getToUserName(), appKey);
        if (StringUtils.isBlank(currentGameName) || !currentGameName.equalsIgnoreCase(getNickName())) {
            return "";
        }

        TextMessage textMessage = new TextMessage(baseMessage);
        //判断是否是内蒙移动手机号
        int telType = ValidateUtil.isYiDong(content);
        if (telType != 0) {
            if (telType == -1) {
                textMessage.setContent(getMsgTelNotKnow());
            } else if (telType == 1) {
                textMessage.setContent(getMsgTelNotNeiMengCMCC());
            } else if (telType == -2) {
                return "";
            } else if (telType == -3) {
                textMessage.setContent(msgTelException);
            }
            return MessageUtil.textMessageToXml(textMessage);
        }

        //判断今天是否输入过游戏名字
        if (!hasInputGameNameToday(baseMessage.getToUserName(), appKey)) {
            textMessage.setContent(getMsgTelWithoutGameName());
        } else {
            //判断手机号是否中奖
            String result = telJoinCountToday(content, baseMessage.getToUserName(), appKey);
            if (StringUtils.isNotBlank(result)) {
                textMessage.setContent(result);
            } else {
                textMessage.setContent("很遗憾，在新春有礼活动中您未中奖，感谢您的支持。");
            }
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    public String queryPrize() {
        if (StringUtils.isBlank(getAppIds()) || getAppIds().contains(appKey)) {
            String result = inputGameName2();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

            result = inputTelephone2();
            if (StringUtils.isNotBlank(result)) {
                return result;
            }

        }
        return "";
    }


    //输入手机号之后的逻辑
    @Override
    protected String gameUrl() {
        TextMessage textMessage = new TextMessage(baseMessage);
        textMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
        if (updateGame(appKey, baseMessage.getToUserName(), getNickName(), content, null, null)) {
            textMessage.setContent("请上传“" +getName()+"”活动相关宣传图文的分享或转发截图，开抢1G、500M流量礼包。");
        } else {
            textMessage.setContent(msgTelException);
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    @Override
    public String getMsgAfterImage() {
        TextMessage textMessage = new TextMessage(baseMessage);
        textMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
        String fileName = UUID.randomUUID().toString() + ".png";
        if(download(content, fileName, descImgFolder)) {
            if (updateGame(appKey, baseMessage.getToUserName(), getNickName(), null, getNickName() + "/" + fileName, null)) {
                textMessage.setContent("您的图片已经上传成功，请耐心等待审核。");
            } else {
                textMessage.setContent(msgTelException);
            }
        } else {
            textMessage.setContent(msgTelException);
        }
        return MessageUtil.textMessageToXml(textMessage);
    }

    public boolean download(String urlString, String filename,String savePath) {
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(urlString);
            URLConnection con = url.openConnection();
            con.setConnectTimeout(10 * 1000);
            is = con.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            File sf = new File(savePath);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            os = new FileOutputStream(sf.getPath() + File.separator + filename);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            is.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public String getAppIds() {
        return "wx940fdc566fac172a";
    }

    @Override
    public String getMemberCode() {
        return null;
    }

    @Override
    public Integer getMemberStatus() {
        return null;
    }

    @Override
    public String getName() {
        return "新春有礼";
    }

    @Override
    public String getNickName() {
        return "shareOneImage";
    }

    @Override
    public String getStartDate() {
        return "2015-02-14";
    }

    @Override
    public String getEndDate() {
        return "2015-03-06";
    }

    @Override
    public String getMsgAfterGameName() {
        return "请输入内蒙移动手机号码查询【" + getName() + "】活动中奖记录";
    }

    @Override
    public String wechatJoinCountToday(String openId, String appKey) {
        //已经中奖的微信号不允许再参加
        PlayGame condition = new PlayGame();
        condition.setGameName(getNickName());
        condition.setAppId(appKey);
        condition.setOpenId(openId);
        condition.setPrize(1);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() > 0) {
                    //表示已经中奖
                    for (LinkedHashMap<String, Object> map : respData) {
                        if (map.get("finishTime") != null && StringUtils.isNotBlank(map.get("finishTime").toString())
                                || map.get("prize") != null && "1".equals(map.get("prize").toString())) {
                            String finishTime = DateTimeUtil.parseDate(Long.parseLong(map.get("finishTime").toString()));
                            String tel = map.get("tel").toString();
                            int num = getPrizeOfAudited(tel);
                            if (num == -1) {
                                return msgTelException;
                            } else {
                                String prizeStr = "500M流量";
                                if (num <= 100) {
                                    prizeStr = "1G流量";
                                }
                                return "您的手机号码" + tel + "，在" + finishTime + "已经获得"+prizeStr+"，谢谢参与【" + getName() +"】活动~";
                            }
                        }
                    }

                    //表示未中奖
                    return "";
                } else {
                    //表示未中奖
                    return "";
                }
            } else {
                return msgTelException;
            }
        } else {
            return msgTelException;
        }
    }

    @Override
    public String telJoinCountToday(String tel, String openId, String appKey) {
        //已经中奖的手机号不允许再参加
        PlayGame condition = new PlayGame();
        condition.setGameName(getNickName());
        condition.setTel(tel);
        condition.setPrize(1);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (respData != null && respData.size() > 0) {
                    //表示已经中奖
                    for (LinkedHashMap<String, Object> map : respData) {
                        if (map.get("finishTime") != null && StringUtils.isNotBlank(map.get("finishTime").toString())
                                || map.get("prize") != null && "1".equals(map.get("prize").toString())) {
                            String finishTime = DateTimeUtil.parseDate(Long.parseLong(map.get("finishTime").toString()));
                            int num = getPrizeOfAudited(tel);
                            if (num == -1) {
                                return msgTelException;
                            } else {
                                String prizeStr = "500M流量";
                                if (num <= 100) {
                                    prizeStr = "1G流量";
                                }
                                return "该手机号码" + tel + "，在" + finishTime + "参与新春有礼活动获得"+prizeStr+"，" +
                                        "由于活动期间成绩排名实时变动，您所收到的回执信息可能与实际情况不符，请以此条查询信息为准，敬请谅解。";
                            }
                        }
                    }

                    //表示未中奖
                    return "";
                } else {
                    //表示未中奖
                    return "";
                }
            } else {
                return msgTelException;
            }
        } else {
            return msgTelException;
        }
    }

    @Override
    public String getMsgImageWithoutTel() {
        return "请输入内蒙古移动手机号码后，再上传图片~";
    }

    /**
     * 获得已审核的个数
     */
    public int getNumberOfAudited() {
        PlayGame condition = new PlayGame();
        condition.setPrize(1);
        condition.setGameName(getNickName());
        Date now = new Date();
        condition.setStartTime(DateTimeUtil.getDateStartMillis(now));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(now));
        CompositeResponse<BaseResponse> thePlayGame = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (thePlayGame.isSuccessful()) {
            BaseResponse theResp = thePlayGame.getSuccessResponse();
            if (theResp.getSuccess()) {
                List<LinkedHashMap<String, Object>> theDate = (List<LinkedHashMap<String, Object>>) theResp.getData();
                if (theDate != null) {
                    return theDate.size();
                }
                return 0;
            }
        }
        return -1;
    }

    public int getPrizeOfAudited(String tel) {
        PlayGame condition = new PlayGame();
        condition.setPrize(1);
        condition.setGameName(getNickName());
        condition.setTel(tel);
        CompositeResponse<BaseResponse> thePlayGameData = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (thePlayGameData.isSuccessful()) {
            BaseResponse theRespData = thePlayGameData.getSuccessResponse();
            if (theRespData.getSuccess()) {
                List<LinkedHashMap<String, Object>> theData = (List<LinkedHashMap<String, Object>>) theRespData.getData();
                if (theData != null && theData.size() > 0) {
                    Date prizeDate = new Date(Long.parseLong(theData.get(0).get("finishTime").toString()));
                    condition.setTel(null);
                    condition.setStartTime(DateTimeUtil.getDateStartMillis(prizeDate));
                    condition.setEndTime(DateTimeUtil.getDateEndMillis(prizeDate));
                    condition.setPageNo(1L);
                    condition.setPageSize(200L);
                    CompositeResponse<BaseResponse> thePlayGame = MyRopClient.getRopClient("").buildClientRequest()
                            .post(condition, BaseResponse.class, "playGame.listByPage", "1.0");
                    if (thePlayGame.isSuccessful()) {
                        BaseResponse theResp = thePlayGame.getSuccessResponse();
                        if (theResp.getSuccess()) {
                            List<LinkedHashMap<String, Object>> theDate = (List<LinkedHashMap<String, Object>>) theResp.getData();
                            if (theDate != null) {
                                int prizeNum = 1;
                                for (LinkedHashMap<String, Object> hashMap : theDate) {
                                    if (hashMap.get("tel") != null && tel.equalsIgnoreCase(hashMap.get("tel").toString())) {
                                        return prizeNum;
                                    } else {
                                        prizeNum++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return -1;
    }

    /**
     * @param result 图片地址
     * @param grade 状态（大于0: 审核通过；-1: 自动删除；-2: 手动删除）
     */
    public boolean updateGame(String appId, String openId, String gameName, String tel, String result, String grade) {
        PlayGame condition = new PlayGame();
        condition.setAppId(appId);
        condition.setOpenId(openId);
        condition.setGameName(gameName);
        Date now = new Date();
        condition.setStartTime(DateTimeUtil.getDateStartMillis(now));
        condition.setEndTime(DateTimeUtil.getDateEndMillis(now));

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "playGame.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                try {
                    PlayGame playGame = new PlayGame();
                    if (StringUtils.isNotBlank(result)) {
                        playGame.setResult(result);

                        Long finishTime = DateTimeUtil.getDateMillis(new Date());
                        playGame.setFinishTime(finishTime);
                    }
                    Integer intGrade = null;
                    if (StringUtils.isNotBlank(grade) && StringUtils.isNumeric(grade)) {
                        intGrade = Integer.parseInt(grade);
                    }
                    playGame.setPrize(intGrade);
                    if (StringUtils.isNotBlank(tel)) {
                        playGame.setTel(tel);
                    }

                    if (respData != null && respData.size() > 0) {
                        if (respData.get(0).get("finishTime") != null) {
                            //新增一条游戏记录
                            playGame.setAppId(appId);
                            playGame.setOpenId(openId);
                            playGame.setGameName(gameName);
                            if (StringUtils.isBlank(tel) && respData.get(0).get("tel") != null) {
                                playGame.setTel(respData.get(0).get("tel").toString());
                            }
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                            return true;
                        } else {
                            //更新游戏
                            Long id = Long.parseLong(respData.get(0).get("id").toString());
                            playGame.setId(id);
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(playGame, BaseResponse.class, "playGame.updateGame", "1.0");
                            return true;
                        }
                    } else {
                        //新增一条游戏记录
                        playGame.setAppId(appId);
                        playGame.setOpenId(openId);
                        playGame.setGameName(gameName);
                        if (StringUtils.isBlank(tel) && respData.get(0).get("tel") != null) {
                            playGame.setTel(respData.get(0).get("tel").toString());
                        }
                        MyRopClient.getRopClient("").buildClientRequest()
                                .post(playGame, BaseResponse.class, "playGame.insert", "1.0");
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    public String getMsgGameNotStart() {
        return "亲！您也太着急了，活动将于02月14日开始，请大家卯足劲，准备开抢。";
    }

    @Override
    public String getMsgGameIsEnd() {
        return getName() + "活动已结束，您所获得的流量将于近日送出，感谢您关注内蒙古移动E生活。";
    }
}
